var powerPage = function () {

    var dataTable;
    var $table = $("#dataTable");
    /**
     * dataTable事件初始化方法
     */

    var onSortColumn = function (sortColumn, sortDirection) {
        switch(sortColumn) {
            case "powerName":
                sortColumn = "pp.`power_name`";
                break;
            case "powerCaseName":
                sortColumn = "poc.`power_case_name`";
                break;
            case "createTime":
                sortColumn = "poc.`create_time`";
                break;
        }
        return customGlobal.onSortColumnDefault(sortColumn, sortDirection);
    };

    var handleRecords = function () {
        dataTable = new Datatable();
        dataTable.init({
            src: $table,
            onQuery: function (data) {
                data.powerName = $("#powerNameQuery").val().trim();
                data.powerCaseName = $("#caseNameQuery").val().trim();
            },
            onSortColumn : onSortColumn,
            dataTable: {
                "ajax": {
                    "url": basePath + "power/getPowerListPage"
                },
                "columns": [
                    {data: 'powerName', orderable: true, searchable: true},
                    {data: 'powerCaseName', orderable: true, searchable: true},
                    {data: 'createTime', orderable: true, searchable: true},
                    {data: 'createName', orderable: false, searchable: false},
                    {data: 'operate', orderable: false,
                        render: function (data, type, full) {
                            var userId=$("#userId").val();
                            var adminRole=$("#adminRole").val();
                            if(adminRole=="1"||userId==full.createId){
                                return '<a class="share btn default btn-xs purple" caseId="' + full.powerCaseId + '"><i class="fa fa-edit"></i>分享</a>&nbsp;'
                                    + '<a class="delete btn default btn-xs black" data-target="#confirmDialog" data-toggle="modal"><i class="fa fa-times"></i>'+i18n["delete"]+'</a>&nbsp;'
                                    + '<a class="edit btn default btn-xs yellow"' +
                                    ' powerCaseName="'+full.powerCaseName+'" powerId="'+full.powerId+'"' +
                                    ' caseId="' + full.powerCaseId + '"><i class="fa fa-edit"></i>编辑</a>&nbsp;'
                                    +'<a class="open btn default btn-xs green" caseId="' + full.powerCaseId + '"><i class="fa fa-plus-square"></i>打开</a>&nbsp;'
                            }else{
                              return '<a class="open btn default btn-xs green" caseId="' + full.powerCaseId + '"><i class="fa fa-plus-square"></i>打开</a>&nbsp;'
                            }

                        }
                    }
                ]
            }
        });
    };

    var handleEvents = function() {
        $table.find('a.delete').live('click', function () {
            var $this = $(this);
            $("#confirmBtn").off("click.deleteRow").on("click.deleteRow", function () {
                var $row = $table.DataTable().row($this.parents('tr')[0]);
                $.ajax({
                    url: basePath + "power/delCase?id=" + $row.data().powerCaseId,
                    dataType: "json",
                    type: "DELETE"
                }).done(function(data) {
                    if(customGlobal.ajaxCallback(data)) {
                        $table.DataTable().draw();
                        $("#confirmDialog").modal("hide");
                    }
                })
            })
        });

        $table.on('click','a.open',function() {
            window.location.href = basePath + "power/openPower?caseId=" + $(this).attr("caseId");
        });

        $("#addPower").off().on('click', function () {
            $("#modalTitlePower").html("新建电厂");
            customGlobal.clearFormAndShowDialog("modalDialogPower");
            $("#addPowerBtn").on('click', function () {
                if ($("#dialogFormPower").validate().form()) {
                    $.ajax({
                        url: basePath + "power/addPowerOnly",
                        type: "post",
                        dataType: "json",
                        data: {
                            powerName: $("#powerName").val()
                        }
                    }).done(function (data) {
                            $('#modalDialogPower').modal('hide');
                            $("<option>").attr("selected", false);
                            var html = "<option value='" + data.powerId + "' selected='selected'>" + data.powerName + "</option>";
                            $("#power").append(html);
                            $("#powerEdit").append(html);
                        })
                }
            })

        });

        $("#addCase").on('click',function() {
            $("#modalTitle").html("新建方案");
            customGlobal.clearFormAndShowDialog("modalDialog");
            $("#power").select2();
            $("#users").select2();

            $("#addBtn").off().on('click',function() {
                if ($("#dialogForm").validate().form()) {
                    var data = {
                        powerId:$("#power").val(),
                        powerCaseName:$("#caseName").val(),
                        tempUserIds:$("#users").val()
                    };
                    $.ajax({
                        url: basePath + "power/addCase",
                        contentType: "application/json; charset=utf-8",
                        type:"post",
                        data:JSON.stringify(data)
                    }).done(function(data) {
                        if (customGlobal.ajaxCallback(data)) {
                            $("#modalDialog").modal('hide');
                            dataTable.reloadTable();
                        }
                    })
                }
            })
        });

        $table.on('click', 'a.edit', function () {
            customGlobal.clearFormAndShowDialog("modalDialogEdit");
            var $this = $(this);
            $("#powerEdit").select2();
            $("#powerEdit").select2("val", $this.attr("powerId"));
            $("#caseEditName").val($this.attr("powerCaseName"));
            $("#editCaseId").val($this.attr("caseId"));
            $("#editBtn").off().on('click', function () {
                if ($("#dialogEditForm").validate().form()) {
                    var data = {
                        powerCaseId: $("#editCaseId").val(),
                        powerId: $("#powerEdit").val(),
                        powerCaseName: $("#caseEditName").val()
                    };
                    $.ajax({
                        url: basePath + "power/editCase",
                        contentType: "application/json; charset=utf-8",
                        type: "post",
                        data: JSON.stringify(data)
                    }).done(function (data) {
                        if (customGlobal.ajaxCallback(data)) {
                            $("#modalDialogEdit").modal('hide');
                            dataTable.reloadTable();
                        }
                    })
                }
            })
        })
        $table.on('click','a.share',function() {
            var $this = $(this);
            $("#modalTitleShare").html("方案分享");
            $.get(basePath + "power/getUserIds?caseId=" + $this.attr("caseId"),function(data) {
                customGlobal.clearFormAndShowDialog("modalDialogShare");
                var $userList = $("#usersShare");
                $("#caseId").val($this.attr("caseId"));
                for (var i = 0; i < data.length; i++) {
                    var str = "option[value=" + data[i] + "]";
                    $userList.find(str).attr("selected", "selected")
                }
                $userList.select2();
            });

            $("#addShareBtn").on('click',function() {
                var data = {
                    powerCaseId:$("#caseId").val(),
                    tempUserIds:$("#usersShare").val()
                };
                $.ajax({
                    url: basePath + "power/updateShare",
                    contentType: "application/json; charset=utf-8",
                    type:"post",
                    data:JSON.stringify(data)
                }).done(function(data) {
                    if (customGlobal.ajaxCallback(data)) {
                        $("#modalDialogShare").modal('hide');
                    }
                })
            })
        })
    };

    return {

        init: function () {
            handleRecords();
            handleEvents();
        }
    }
}();